#include "threadPool.h"


CThreadPool::CThreadPool(size_t threads):m_stop(false)
{
	for (size_t i = 0; i < threads; ++i)
	{
		m_vecWorkers.emplace_back([this]() {
			while (1)
			{
				std::function<void()> task;

				{
					std::unique_lock<std::mutex> lock(this->m_queue_mutex);
					this->m_condition.wait(lock, [this]() {
						if (this->m_stop || !this->m_queTasks.empty())
						{
							return true;
						}
						return false;
					});

					if (this->m_stop && this->m_queTasks.empty())
					{
						return;
					}

					task = std::move(this->m_queTasks.front());
					this->m_queTasks.pop();
				}

				task();

			}

		});
	}
}


CThreadPool::~CThreadPool()
{
	Stop();

	m_condition.notify_all();// 唤醒所有线程，清理任务
	for (std::thread& worker : m_vecWorkers)
	{
		worker.join();// 阻塞，等待所有线程执行结束
	}

}

void CThreadPool::Stop()
{
	std::unique_lock<std::mutex> lock(this->m_queue_mutex);
	m_stop = true;
}